#include <stdarg.h>

#include "config.h"
#undef DebugChanel
#define DebugChanel 0

void Uart0_Init(void);
void Uart0_PutChar(char cData);
char Uart0_GetChar();
void Uart0_PutString(char *pcData, int iLen);
void Uart0_Printf(const char *pcFmt, ...);

void Uart0_Init(void)
{
    uint16 usFdiv;

    U0LCR = 0x83;
    usFdiv = (Fpclk / 16) /115200;
    U0DLM = usFdiv /256;
    U0DLL = usFdiv % 256;
    U0LCR = 0x03;
    U0FCR = 0xC1;
    U0IER = 0x01;
}

void Uart0_PutChar(char cData)
{
    while((U0LSR & 0x40) == 0);
    U0THR = cData;
}

char Uart0_GetChar()
{
    char cTmpData;
    
    while((U0LSR & 0x01) == 0);
    cTmpData  = U0RBR;

    return cTmpData;
}

void Uart0_PutString(char *pcData, int iLen)
{
    int iTmp = 0;
    
    while((pcData !=  '\0')  &&  (iTmp < iLen))
    {
        Uart0_PutChar(*pcData);
        pcData++;
        iTmp++;
    }
}

void Uart0_Printf(const char *pcFmt, ...)
{
    va_list vlArgs;
    unsigned char iTmp;
    char pcPrintBuffer[400];

    va_start(vlArgs, pcFmt);
    /* For this to work, printbuffer must be larger than
    * anything we ever want to print.
    */
    iTmp = vsprintf(pcPrintBuffer, pcFmt, vlArgs);
    va_end(vlArgs);

    Uart0_PutString(pcPrintBuffer, iTmp);
}
